import axios from 'axios';

import DataModel from 'framework/datamodel';
import Api from '@/util/api'
import DataSetModel from 'framework/datamodel/DataSetModel'

export default class DataSource {
  _datas = [];
  _total = 0;
  _status = false;
  _items ={};
  _configs = {
    source: null,
  };
  _request = null;
  _otherparam = null;

  _params = {
    page: 1,
    size: 10,
    sort: 'createdTime,desc',
    search: null,
  };

  page(page = null) {
    if (page !== null) {
      this._params.page = page;
    }

    return this._params;
  }
  constructor(config = null,data) {
    if (config !== null) {
      this._configs = config;
      if (this._configs.hasOwnProperty('size')) {
        this._params.size = this._configs.size;
      }
      if (this._configs.hasOwnProperty('sort')) {

        this._params.sort = this._configs.sort;
      }
      if (this._configs.hasOwnProperty('search')) {

        this._params.search = this._configs.search;
      }
    }
    if(data !==null){
      this._items = data
    }
  }

  datas() {
    return this._datas;
  }

  total() {
    return this._total;
  }

  status(status = null) {
    if (status !== null) {
      this._status = status;
    }
    return this._status;
  }

  async _updateDatas() {
    let tmpparams = {};
    let tmpparams1 = Object.assign(tmpparams,this._params,this._otherparam,this._items);

    console.info("call _updateDatas " + this._params + "," + this._otherparam);
    const response = await Api.get(this._configs.source, {
      params: tmpparams1
    });
    let dataSetModel = new DataSetModel(response.data[this._configs.result]);
    this._datas = dataSetModel.datas;
    this._total = dataSetModel.total;
    return dataSetModel
  }

  async updatePage(search = null) {
    console.info("call updatePage");

    this.status('loading');
    if (search !== null) {
      this._params.search = search;
    }
    await this._updateDatas();
    this.status('complete');
  }

  findData(find) {
    console.info("call findData");

    for (let data of this._datas) {
      if (find.call(null, data) === false) {
        return;
      }
    }
  }

  async search(search = null,otherparam= null) {
    console.info("call search " + search + "," + otherparam);
    this.status('loading');
    if (search !== null) {
      this._params.search = search;
    }
    if(otherparam !== null)
    {
      this._otherparam = otherparam;
    }
    await this._updateDatas();
    this.status('complete');
  }

}
